import express from "express";
import session from "express-session";

// 导入路由
import userRouter from "./router/user.js";
import todoRouter from "./router/todo.js";

const app = express();
// 静态文件服务
app.use(express.static("public"));
// 设置模板引擎
app.set("view engine", "ejs");
// 设置模板文件的存放目录
app.set("views", "./views");
// 解析请求体
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 初始化 session
app.use(
  session({
    secret: "my-secret-key",
    resave: false,
    saveUninitialized: false,
    cookie: {
      maxAge: 60 * 60 * 1000 * 24, // 24小时
      httpOnly: false,
      secure: false,
    },
  })
);

// 注册路由
app.use("/api", userRouter);
app.use("/api", todoRouter);

// 全局错误处理
app.use((err, req, res, next) => {
  console.error(err);
  res
    .status(500)
    .json({ success: false, message: "服务器内部错误", detail: err.message });
});

app.listen(3000, () => {
  console.log("Server running on port 3000: http://localhost:3000");
});
